import React, { PureComponent } from 'react'
import { connect } from 'react-redux'
import { createSetPageErrorAction } from '@/redux/actions/pageError'
import { Checkbox, Button, WhiteSpace, Toast } from 'antd-mobile'
import Avatar from '@/components/Avatar'
import VoteComments from '@/components/Comment'
import css from './index.module.scss'
import { voteApi } from '@/api'
class Vote extends PureComponent {

    state = {
        info: null,
        voteOptions: null,
        maxVoteOption: 0,
        nextPageId: null,
        voteComments: []
    }

    get id() {
        const { match: { params: { id } } } = this.props
        return id
    }

    get hasInfo() {
        return !!this.state.info
    }

    get voting() {
        let flag = false
        if (this.hasInfo) {
            flag = this.state.info.endtime * 1000 > new Date().getTime()
        }
        return flag          
    }

    get selectedVoteOptions() {
        let arr = []
        if (this.hasInfo) {
            arr = this.state.info.options.filter(item => item.checked)
        }
        return arr
    }

    initData = async () => {
        try {
            await this.getInfo()
            await this.getComments()            
        } catch (error) {
            this.props.setPageError(true)
        }
    }

    getInfo = async () => {
        try {
            const { data } = await voteApi.getInfo({
                vote_id: this.id
            })
            const { info, info: { cnt, options, uid } } = data
            if (uid === 0) {
                throw new Error('没有用户信息')
            }

            const cnts = []
            options.forEach(option => {
                if (option.cnt) {
                    cnts.push(option.cnt)
                    option.percentage = (option.cnt / cnt * 100).toFixed(2) + '%'
                } else {
                    option.percentage = '0.00%'
                }
                option.checked = false
            })
            if (cnts.length) {
                this.setState({
                    maxVoteOption: Math.max(...cnts)
                })
            }
            this.setState({
                info
            })
        } catch (error) {
            throw new Error(error)
        }
    }

    getComments = async () => {
        try {
            const { data } = await voteApi.getComments({
                oid: this.id,
                mode: 3,
                next: this.state.nextPageId
            }) 
            const { replies, cursor, cursor: { next } } = data
            const { voteComments } = this.state 
            this.setState({
                nextPageId: next
            })               
            if (cursor.is_end) {
                // this.$refs.refreshList.completeLoad()
            } else {
                this.setState({
                    voteComments: [...voteComments, ...replies]
                })
            }
        } catch (error) {
            
        }
    }

    leftTime = (value) => {
        const endtime = value * 1000
        const nowtime = new Date().getTime()
        const left = endtime - nowtime
        if (left >= 0) {
          const leftDay = Number.parseInt(left / (24 * 60 * 60 * 1000))
          const leavel = left % (24 * 3600 * 1000)
          const leftHours = Math.floor(leavel / (3600 * 1000))
          const leavel2 = leavel % (3600 * 1000)
          const leftMinutes = Math.floor(leavel2 / (60 * 1000))
          return `剩余${leftDay}天${leftHours}时${leftMinutes}分`
        }
    }
    
    handleSpace = id => {
        this.props.history.push(`/space/${id}`)
    }

    handleCheck = item => {
        const { idx, checked } = item
        const { info } = this.state
        const { options, choice_cnt } = info
        if (!checked && this.selectedVoteOptions.length === choice_cnt) {
            Toast.info(`最多只能选择${choice_cnt}项`, 3)
            return
        }
        const matchOption = options.find(option => option.idx === idx)
        matchOption.checked = !checked
        this.setState({
            info: {...info}
        })
    }

    handleVote = () => {
        Toast.info('功能开发中', 3)
    }

    componentDidMount() {
        this.initData()
    }

    componentDidUpdate(prevProps) {
        const prevId = prevProps.match.params.id
        if (prevId !== this.id) {
            this.initData()
        }
    }

    render() {
        const { info, voteComments } = this.state
        return (
            <>
                {
                    info && 
                    <div className={css["wrap"]}>
                        <div className="head">
                            <div className="head-main">
                                <div className="vote-title">{ info.title }</div>
                                <div className="vote-creator" onClick={() => this.handleSpace(info.uid)}>
                                    <Avatar
                                        className="avatar"
                                        size="small"
                                        src={info.face}
                                        vip={-1}
                                    />
                                    <span className="user-name">{ info.name }</span>
                                    <span className="user-text">发起</span>
                                    { this.voting && <span className="user-text">{ this.leftTime(info.endtime) }</span> }
                                </div>
                            </div>
                            <div className="head-aside">
                                <span className="num">{ info.cnt }</span>
                                <span>参与人数</span>
                            </div>
                        </div>
                        <div className="checkbox-head">
                            <span className="title">投票选项</span>
                            <span className="count">最多选{info.choice_cnt}项</span>
                        </div>
                        <ul className="checkbox-wrap">
                            {
                                info.options.map(item => {
                                    return (
                                        <li key={item.idx} onClick={() => this.handleCheck(item)}>
                                            <div className="option-content">
                                                { !this.voting && <div className="precentage-bar" style={{'width': item.percentage}}></div> }
                                                <div className="vote-desc">
                                                    <div className="option-text">{ item.desc }</div>
                                                    { !this.voting && <div className="vote-count">{ item.cnt }票</div> }
                                                </div>
                                                { !this.voting && <div className="vote-percentage">{ item.percentage }</div> }
                                                { this.voting && <div className="vote-checkbox">                                                           
                                                    <Checkbox.CheckboxItem checked={item.checked} />
                                                </div> }
                                            </div>
                                        </li>
                                    )
                                })
                            }
                        </ul>
                        <WhiteSpace size="md" />
                        { this.voting && <Button type="primary" disabled={this.selectedVoteOptions.length === 0} onClick={this.handleVote}>投票</Button> }
                        { !this.voting && <Button type="primary" disabled={true}>投票已结束</Button> }                          
                        <WhiteSpace size="md" />
                        <div className="foot">
                            { voteComments.length > 0 && <VoteComments comments={voteComments} /> }
                        </div>
                    </div>
                }    
            </>            
        )                
    }
}

export default connect(
    null,
    {
        setPageError: createSetPageErrorAction
    }
)(Vote)